import openpyxl
from django.http import HttpResponse
from datetime import datetime
from .utils import insert_excel_by_cell, safe_int

# 导出订单到Excel的通用函数
def export_orders_to_excel(orders, order_type='转运订单'):
    try:
        wb = openpyxl.Workbook()
        sheet = wb.active
        sheet.title = order_type
        font_size = 12
        width = 35
        height = 55
        # 插入表头
        headers = [
            ('A1', '订单号'), ('B1', '物流员'), ('C1', '发货方式'), ('D1', '佐川金额'),
            ('E1', '黑猫金额'), ('F1', '都道府県'), ('G1', '邮编'), ('H1', '地址1'),
            ('I1', '地址2'), ('J1', '城市'), ('K1', '电话'), ('L1', '收货人'),
            ('M1', '公司'), ('N1', '创建时间'), ('P1', '黑猫运费总和'), ('Q1', '佐川运费总和'), ('R1', '运费差额'),
        ]
        for cell, header in headers:
            insert_excel_by_cell(
                sheet,
                cell,
                header,
                font_size=font_size,
                is_bold=True,
                has_border=True,
                width=width,
                height=height,
                fill_color='93A9D7'  # 使用蓝色背景
            )

        # 计算总和
        yamato_total = sum(float(order.yamato_price or 0) for order in orders)
        sagawa_total = sum(float(order.sagawa_price or 0) for order in orders)
        fee_difference = yamato_total - sagawa_total

        # 写入总和数据
        insert_excel_by_cell(sheet,'P2',yamato_total,font_size=font_size,is_bold=True,has_border=True,width=width,height=height,fill_color='E6B8B7')
        insert_excel_by_cell(sheet,'Q2',sagawa_total,font_size=font_size,is_bold=True,has_border=True,width=width,height=height,fill_color='E6B8B7')
        insert_excel_by_cell(sheet,'R2',fee_difference,font_size=font_size,is_bold=True,has_border=True,width=width,height=height,fill_color='E6B8B7')
        insert_excel_by_cell(sheet,'S2',fee_difference,font_size=font_size,is_bold=True,has_border=True,width=width,height=height,fill_color='E6B8B7')
        for index, order in enumerate(orders, start=2):
            order_no = order.cw_no if hasattr(order, 'cw_no') else order.fs_no
            row_data = [('A', order_no),('B', order.created_by.username if order.created_by else ''),('C', order.shipping_method),('D', order.sagawa_price),('E', order.yamato_price),('F', order.state),('G', order.postal_code),('H', order.address1),('I', order.address2),('J', order.city),('K', order.phone_number),('L', order.attention),('M', order.company_name),('N', order.create_time.strftime('%Y-%m-%d %H:%M:%S') if order.create_time else '')]
                        
            for col, value in row_data:
                cell = f"{col}{index}"
                insert_excel_by_cell(sheet,cell,value,font_size=font_size,is_bold=False,has_border=True,width=width,height=height,fill_color='ffffff')
        filename = f'{order_type}{datetime.now().strftime("%Y%m%d_%H%M%S")}.xlsx'
        response = HttpResponse(
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        response['Access-Control-Expose-Headers'] = 'Content-Disposition'
        
        # 保存Excel到响应
        wb.save(response)
        return response

    except Exception as e:
        raise Exception(f'导出失败: {str(e)}')


# 处理本地订单数据
def process_local_orders(orders):
    local_order_count_total = 0
    local_order_box_count_total = 0
    local_order_is_changecode_count = 0
    local_order_changecode_id_count = 0
    local_order_changecode_box_count = 0
    local_order_is_pickup_count = 0
    local_order_pickup_box_count = 0
    local_order_yamato_price_total = 0
    local_order_sagawa_price_total = 0

    for order in orders:
        local_order_count_total += 1
        local_order_box_count_total += safe_int(order.box_count)
        local_order_yamato_price_total += safe_int(order.yamato_price)
        local_order_sagawa_price_total += safe_int(order.sagawa_price)

        # 改码单统计（包括改码+自提的订单，改码+自提只算改码单）
        if order.is_changecode:
            local_order_is_changecode_count += 1
            local_order_changecode_id_count += safe_int(order.changecode_id_count)
            local_order_changecode_box_count += safe_int(order.box_count)
        
        # 自提单统计（只统计纯自提单，不包括改码+自提）
        if order.is_pickup and not order.is_changecode:
            local_order_is_pickup_count += 1
            local_order_pickup_box_count += safe_int(order.box_count)

    # 计算常规订单数据（既不是改码也不是自提的订单）
    regular_order_count = 0
    regular_order_box_count = 0
    
    for order in orders:
        if not order.is_changecode and not order.is_pickup:
            regular_order_count += 1
            regular_order_box_count += safe_int(order.box_count)

    return {
        'change_code': {
            'is_changecode_count': local_order_is_changecode_count,
            'changecode_id_count': local_order_changecode_id_count,
            'changecode_box_count': local_order_changecode_box_count,
        },
        'pickup': {
            'is_pickup_count': local_order_is_pickup_count,
            'is_pickup_box_count': local_order_pickup_box_count,
        },
        'regular_total': {
            'local_order_count_total': regular_order_count,
            'local_order_box_count_total': regular_order_box_count,
        },
        'price': {
            'local_order_yamato_price_total': local_order_yamato_price_total,
            'local_order_sagawa_price_total': local_order_sagawa_price_total,
        },
    }

# 闭包
def create_order_processor(order_type_prefix):
    def processor(orders):
        # 通用统计变量
        stats = {
            'count_total': 0,
            'box_count_total': 0,
            'yamato_price_total': 0,
            'sagawa_price_total': 0,
            'pickup_count': 0,
            'pickup_box_count': 0,
            'changecode_count': 0,
            'changecode_box_count': 0,
            'changecode_id_count': 0,
            'id_count_total': 0,
            'order_count_total': 0,
        }
        
        # 统计订单数据
        for order in orders:
            # 基础统计
            if hasattr(order, 'order_count'):
                stats['order_count_total'] += safe_int(order.order_count)
            else:
                stats['count_total'] += 1
                
            stats['box_count_total'] += safe_int(order.box_count)
            
            # 价格统计（如果存在）
            if hasattr(order, 'yamato_price'):
                stats['yamato_price_total'] += safe_int(order.yamato_price)
                stats['sagawa_price_total'] += safe_int(order.sagawa_price)
            
            # ID数量统计（如果存在）
            if hasattr(order, 'id_count'):
                stats['id_count_total'] += safe_int(order.id_count)
            
            # 改码统计（本地单专有，包括改码+自提的订单，改码+自提只算改码单）
            if hasattr(order, 'is_changecode') and order.is_changecode:
                stats['changecode_count'] += 1
                stats['changecode_box_count'] += safe_int(order.box_count)
                if hasattr(order, 'changecode_id_count'):
                    stats['changecode_id_count'] += safe_int(order.changecode_id_count)
            
            # 自提统计（只统计纯自提单，不包括改码+自提）
            if (hasattr(order, 'is_pickup') and order.is_pickup and 
                not (hasattr(order, 'is_changecode') and order.is_changecode)):
                stats['pickup_count'] += 1
                stats['pickup_box_count'] += safe_int(order.box_count)
        
        # 计算常规订单数据
        if hasattr(orders.first(), 'is_changecode') if orders.exists() else False:
            # 本地单逻辑：既不是改码也不是自提
            regular_count = sum(1 for order in orders if not getattr(order, 'is_changecode', False) and not getattr(order, 'is_pickup', False))
            regular_box_count = sum(safe_int(order.box_count) for order in orders if not getattr(order, 'is_changecode', False) and not getattr(order, 'is_pickup', False))
        else:
            # 其他订单逻辑
            if hasattr(orders.first(), 'order_count') if orders.exists() else False:
                regular_count = stats['order_count_total'] - stats['pickup_count']
                regular_box_count = stats['box_count_total'] - stats['pickup_box_count']
            else:
                regular_count = stats['count_total'] - stats['pickup_count']
                regular_box_count = stats['box_count_total'] - stats['pickup_box_count']
        
        return stats, regular_count, regular_box_count
    
    return processor

# 转运单
process_transfer_orders = lambda orders: (lambda stats, regular_count, regular_box_count: {
    'pickup': {
        'is_pickup_count': stats['pickup_count'],
        'is_pickup_box_count': stats['pickup_box_count'],
    },
    'regular_total': {
        'transfer_order_count_total': regular_count,
        'transfer_order_box_count_total': regular_box_count,
    },
    'price': {
        'transfer_order_yamato_price_total': stats['yamato_price_total'],
        'transfer_order_sagawa_price_total': stats['sagawa_price_total'],
    },
})(*create_order_processor('transfer')(orders))

# 退换货
process_aftersale_orders = lambda orders: (lambda stats, *_: {
    'aftersale_order_count_total': stats['count_total'],
    'aftersale_order_box_count_total': stats['box_count_total'],
    'aftersale_order_id_count_total': stats['id_count_total'],
})(*create_order_processor('aftersale')(orders))

# 调仓单
process_relocation_orders = lambda orders: (lambda stats, *_: {
    'relocation_order_count_total': stats['order_count_total'],
    'relocation_order_box_count_total': stats['box_count_total'],
    'relocation_order_id_count_total': stats['id_count_total'],
})(*create_order_processor('relocation')(orders))

# 使用闭包创建跨仓单处理器
process_cross_orders = lambda orders: (lambda stats, *_: {
    'cross_order_count_total': stats['order_count_total'],
    'cross_order_box_count_total': stats['box_count_total'],
    'cross_order_id_count_total': stats['id_count_total'],
})(*create_order_processor('cross')(orders))

# 回国单
process_return_orders = lambda orders: (lambda stats, *_: {
    'return_order_count_total': stats['order_count_total'],
    'return_order_box_count_total': stats['box_count_total'],
    'return_order_id_count_total': stats['id_count_total'],
})(*create_order_processor('return')(orders))

# 库存收货单
process_inventory_receive_orders = lambda orders: (lambda stats, *_: {
    'inventory_receive_order_count_total': stats['order_count_total'],
    'inventory_receive_order_box_count_total': stats['box_count_total'],
})(*create_order_processor('inventory_receive')(orders))

# 维修单
process_repair_orders = lambda orders: (lambda stats, *_: {
    'repair_order_count_total': stats['order_count_total'],
    'repair_order_box_count_total': stats['box_count_total'],
    'repair_order_id_count_total': stats['id_count_total'],
})(*create_order_processor('repair')(orders))


